package com.ljb.demompandroidchart.mpchartutils;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;

import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * MPAndroid饼状图的工具类.好的代码不需要注释
 * Created by lijianbin on 2016/12/5.
 */
public class PieUtils implements OnChartValueSelectedListener {

    private String[] mColors = {"#9F6AFF", "#5EC6D3", "#F867B0", "#F8E7B8", "#56FD99D4", "#5651B6FD", "#56A0F4FF", "#56FE9A69", "#56FD9E51", "#56936CAF"};
    private static PieUtils utils;
    private PieChart mChart;
    private int count;
    private PieDataSet dataSet;
    private boolean isUsePercentValues = true;
    private float value;
    private Context mContext;
    private String mColor = "#69758f";
    private String centerText;
    private boolean isShowCenterText = true;

    private PieUtils(Context context) {
        mContext = context;
    }

    /**
     * 获取单例工具类对象
     */
    public synchronized static PieUtils getInstance(Context context) {
//        if (utils == null)
        utils = new PieUtils(context);
        return utils;
    }

    /**
     * 初始化chart
     */
    public PieUtils initChart(PieChart chart) {
        mChart = chart;

        mChart.setUsePercentValues(isUsePercentValues);
        mChart.getDescription().setEnabled(false);
        mChart.setExtraOffsets(10, 10, 10, 10);

        mChart.setDragDecelerationFrictionCoef(0.95f);

        mChart.setDrawHoleEnabled(false);
        mChart.setHoleColor(Color.WHITE);

        mChart.setTransparentCircleColor(Color.WHITE);
        mChart.setTransparentCircleAlpha(110);

        mChart.setHoleRadius(50f);
        mChart.setTransparentCircleRadius(55f);

        mChart.setDrawCenterText(true);

        mChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        mChart.setRotationEnabled(false);
        mChart.setHighlightPerTapEnabled(true);

        // mChart.setUnit(" €");
        // mChart.setDrawUnitsInChart(true);

        mChart.animateY(500, Easing.EasingOption.EaseInOutQuad);
        // mChart.spin(2000, 0, 360);

        // entry label styling
        mChart.setEntryLabelColor(Color.WHITE);
//        mChart.setEntryLabelTypeface(mTfRegular);
        mChart.setEntryLabelTextSize(12f);
        mChart.setOnChartValueSelectedListener(this);
        mChart.setDrawEntryLabels(false);

//        PieMarkView mv = new PieMarkView(mContext, R.layout.pie_marker_view);
//        mv.setChartView(mChart); // For bounds control
//        mChart.setMarker(mv); // Set the marker to the chart

        return this;
    }

    public PieUtils setPercentValues(Boolean isUsePercentValues) {
        mChart.setUsePercentValues(isUsePercentValues);
        mChart.invalidate();
        return this;
    }

    /**
     * 设置图例
     */
    public PieUtils setLegend(boolean isEnable) {

        if (mChart != null) {
            Legend l = mChart.getLegend();
            if (isEnable) {
                l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
                l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
                l.setOrientation(Legend.LegendOrientation.VERTICAL);
                l.setDrawInside(false);
                l.setXEntrySpace(7f);
                l.setYEntrySpace(0f);
                l.setYOffset(0f);
            }
            l.setEnabled(isEnable);
        }
        return this;
    }

    /**
     * 设置数据
     */
    public PieUtils setData(float[] data, String[] parties, String label) {
        if (data.length == parties.length) {
            this.count = data.length;
        } else {
            throw new IllegalStateException("数据集和标签集的长度必须一致");
        }
        ArrayList<PieEntry> entries = new ArrayList();
        for (int i = 0; i < count; i++) {
            value = data[i];
            entries.add(new PieEntry(value, parties[i]));
        }
        dataSet = new PieDataSet(entries, label);
        initDataSet(dataSet);
        initColor(dataSet);
        initData(dataSet);
        setCenterText();
        return this;
    }

    /**
     * 显示图表,必须在最后调用
     */
    public void show() {
        if (mChart != null)
            mChart.invalidate();
    }

    public PieUtils setCenterText(String text) {
        centerText = text;
        return this;
    }

    private void setCenterText() {
        if (mChart != null) {
            if (!isShowCenterText) {
                mChart.setDrawHoleEnabled(false);
                return;
            }
            if (centerText == null) {
                DecimalFormat format = new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                String value = format.format(mChart.getData().getYValueSum());//format 返回的是字符串
                mChart.setCenterText(value);
            } else {
                mChart.setCenterText(centerText);
            }
            mChart.setCenterTextColor(Color.parseColor(mColor));
            mChart.setCenterTextSize(20);
            mChart.setDrawHoleEnabled(true);
        }
    }

    public PieUtils showCenterText(boolean isShow) {
        isShowCenterText = isShow;

        return this;
    }

    public PieUtils setCenterTextSize(float size) {
        if (mChart != null) {
            mChart.setCenterTextSize(size);
        }
        return this;
    }

    /**
     * 为饼状图的每个块设置颜色,必须在setData前调用
     */
    public PieUtils setPieColor(String[] colors) {
        mColors = colors;
        return this;
    }

    private void initDataSet(PieDataSet dataSet) {
        dataSet.setSliceSpace(0f);
//        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);
//        dataSet.setSelectionShift(0f);
    }

    private void initColor(PieDataSet dataSet) {
        if (mColors.length < count) {
            throw new IllegalArgumentException("颜色集合必须比饼状图的块数多");
        }
        ArrayList<Integer> colors = new ArrayList();
        for (int i = 0; i < count; i++)
            colors.add(rgb(mColors[i]));
        dataSet.setColors(colors);
    }

    private void initData(PieDataSet dataSet) {
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        data.setValueTypeface(Typeface.DEFAULT_BOLD);
        mChart.setData(data);
    }

    private int rgb(String hex) {
        int color = (int) Long.parseLong(hex.replace("#", ""), 16);
        int r = (color >> 16) & 0xFF;
        int g = (color >> 8) & 0xFF;
        int b = (color >> 0) & 0xFF;
        return Color.rgb(r, g, b);
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        setPercentValues(false);
//        for (IDataSet<?> set : mChart.getData().getDataSets())
//            set.setDrawValues(false);
        if (mListener != null)
            mListener.onValueSelected(e, h);
    }

    @Override
    public void onNothingSelected() {
        setPercentValues(true);
//        for (IDataSet<?> set : mChart.getData().getDataSets())
//            set.setDrawValues(true);
//        if (mListener != null)
//            mListener.onNothingSelected();
    }

    private OnValueTouchListener mListener;

    public PieUtils setOnValueTouchListener(OnValueTouchListener listener) {
        if (listener != null)
            mListener = listener;
        return this;
    }
}
